package com.comm;

import com.dao.ISyslog;
import com.model.SysLog;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.LocalVariableTableParameterNameDiscoverer;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;


@Order(3)
@Component
@Aspect
public class LogAopAspect {

    @Autowired
    private ISyslog iSyslog;

    @Around("@annotation(com.comm.LogAnno)")
    public Object auoundAd(ProceedingJoinPoint pjp){
        System.out.println("进入环形通知方法");
        //获取方法签名
        MethodSignature methodSignature=(MethodSignature) pjp.getSignature();
        //获取方法
        Method method=methodSignature.getMethod();
        //获取方法上面的注解
        LogAnno logAnno=method.getAnnotation(LogAnno.class);
        String oper=logAnno.OperateType();

        //获取访问接口时的各种操作
        SysLog sysLog=new SysLog();
        sysLog.setUsername("admin");
        sysLog.setOperation("接口描述");
        sysLog.setIp(HttpContextUtil.getIPAddress());

        //请求方法当中的类
        String className=pjp.getTarget().getClass().getName();
        String methodName=methodSignature.getName();
        sysLog.setMethod(className+"."+methodName);

        //请求方法的相关参数
        Object[] args=pjp.getArgs();
        System.out.println("获取参数的长度："+args.length);
        LocalVariableTableParameterNameDiscoverer u=new LocalVariableTableParameterNameDiscoverer();
        String[] paramNames=u.getParameterNames(method);
        System.out.println("方法中所涵盖的参数名称:"+paramNames.length);
        if(args!=null&&paramNames!=null){
            String params="";
            for (int i=0;i<args.length;i++){
                params+=" "+paramNames[i]+":"+args[i];
            }
            sysLog.setParams(params);
        }

        Object result=null;
        try {
            long begin = System.currentTimeMillis();
            try {
                result = pjp.proceed();

            } catch (Throwable e) {
                e.printStackTrace();
            }
            long end = System.currentTimeMillis();
            //执行的时间
            sysLog.setTime(end - begin);

            sysLog.setOperation("正常");
        }catch(Exception e){
            sysLog.setOperation("失败");
        }finally {
            iSyslog.insertLog(sysLog);
            System.out.println("将访问接口的信息记录到数据库中");
        }
        System.out.println("结束环形通知方法");
        return result;
    }

}
